package com.ms.p2p.controller.admin;


import com.alibaba.dubbo.config.annotation.Reference;
import com.ms.common.bean.Message;
import com.ms.common.exception.NoticeException;
import com.ms.common.utils.AppContext;
import com.ms.common.utils.MsDateUtils;
import com.ms.common.utils.excel.ExcelData;
import com.ms.p2p.bean.PageBean;
import com.ms.p2p.controller.BaseController;
import com.ms.p2p.entity.account.AccountBank;
import com.ms.p2p.entity.account.AccountRecharge;
import com.ms.p2p.entity.member.Auth;
import com.ms.p2p.entity.member.Member;
import com.ms.p2p.entity.system.AdminUser;
import com.ms.p2p.plugin.validation.annotation.RequiredStringValidator;
import com.ms.p2p.plugin.validation.annotation.Validations;
import com.ms.p2p.provider.*;
import com.ms.p2p.utils.JsonDataGridHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Controller
@Transactional
@RequestMapping({ "/admin/recharge" })
public class AdminRechargeController extends AdminBaseController {
	@Reference
	private AdminLogProvider adminLogService;

	@Reference
	private MemberAccountRechargeProvider rechargeSerivce;

	@Reference
	private MemberAccountProvider memberAccountProvider;

	@Reference
	private MemberAccountRecordProvider accountLogService;

	@Reference
	private MemberProvider memberProvider;

	@Reference
	private MemberAccountBankProvider memberAccountBankProvider;

	@Reference
	private CertiFiCationProvider certificationProvider;

	@Reference
	private DictionaryProvider dictionaryProvider;


	@RequestMapping(value = {"/queryData"}, produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public PageBean queryData(HttpServletRequest request, HttpSession session
			,@RequestParam(value = "begin_date",required = false) String begin_date
			,@RequestParam(value = "rechargeType",required = false) String rechargeType
			,@RequestParam(value = "payWay",required = false) String payWay
			,@RequestParam(value = "money",required = false) String money
			,@RequestParam(value = "userName",required = false) String userName
			,@RequestParam(value = "trade_no",required = false) String trade_no
			,@RequestParam(value = "status",required = false) String status
			,@RequestParam(value = "end_date",required = false) String end_date
			,PageBean page
	) {
		page.setList( rechargeSerivce
				.findPaager(rechargeType,payWay,money,userName,trade_no,status,begin_date,end_date, page.getBegin(),page.getPageSize()));
		page.setTotalCount(rechargeSerivce.findCount(rechargeType,payWay,money,userName,trade_no,status,begin_date,end_date));
		return JsonDataGridHelper.createJSONData(page);
	}

	/**
	 * 后台充值记录
	 * 
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping({ "/list" })
	public String rechargeList(HttpServletRequest request, HttpSession session)
	{
		return "admin/account/record/recharge/list";
	}

	@RequestMapping({ "/exportRechargeList" })
	public String exportRechargeList(HttpServletRequest request, Model model
			,@RequestParam(value = "begin_date",required = false) String begin_date
			,@RequestParam(value = "rechargeType",required = false) String rechargeType
			,@RequestParam(value = "payWay",required = false) String payWay
			,@RequestParam(value = "userId",required = false) String userId
			,@RequestParam(value = "userName",required = false) String userName
			,@RequestParam(value = "trade_no",required = false) String trade_no
			,@RequestParam(value = "status",required = false) String status1
			,@RequestParam(value = "end_date",required = false) String end_date

	) {
		List<Map<String, Object>> recharges = rechargeSerivce.findPaager(rechargeType,payWay, userId, userName, trade_no, status1, begin_date, end_date, 0, null);

		for (Map<String, Object> map : recharges) {
			Object type = map.get("type");
			if (type != null) {
				map.put("type", dictionaryProvider.getDictValue("recharge_methods",type+""));

			}
			String ra_real_name = (String) map.get("ra_real_name");
			if (StringUtils.isEmpty(ra_real_name)) {
				map.put("ra_real_name", map.get("pany_name"));
			}
			Object money = map.get("money");
			if (money != null) {
				map.put("money", money.toString());
			}
			Object fee = map.get("fee");
			if (fee != null) {
				map.put("fee", fee.toString());
			}
			Object amount = map.get("amount");
			if (amount != null) {
				map.put("amount", amount.toString());
			}
			String addtime = (String) map.get("addtime");
			if (addtime != null) {
				map.put("addtime", MsDateUtils.TimeStamp2DateTime(addtime));
			}
			Integer status = (Integer) map.get("status");
			if (status != null) {
				if (status == 0) {
					Integer ap_style = (Integer) map.get("ap_style");
					if (ap_style != null && ap_style == 0) {
						map.put("status", "审核");
					} else {
						map.put("status", "未付款");
					}

				} else if (status == 1) {
					map.put("status", "充值成功");
				} else {
					map.put("status", "充值失败");
				}

			}

		}
		ExcelData excelData = new ExcelData();
		excelData.setHeads(new String[] { "充值类型", "支付方式", "用户ID", "用户名称",
				"真实姓名", "开户行", "银行卡账号", "充值编号", "订单号", "充值金额", "手续费",
				"到账金额", "充值时间", "充值状态" ,"备注"});
		excelData.setFieldNames(new String[] { "type", "ap_name", "user_id",
				"u_user_name", "ra_real_name", "bank", "bank_cardno", "id",
				"trade_no", "money", "fee", "amount", "addtime", "status","remark" });
		excelData.setDataList(recharges);
		excelData.setModelClass(Map.class);
		model.addAttribute("excelData", excelData);
		model.addAttribute("fileName", "充值记录");
		return "excel";
	}


	/**
	 * 充值详情（审核页面）
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping({ "/{rechargeId}" })
	public String rechargeDetail(HttpServletRequest request,@PathVariable String rechargeId) {
		if (rechargeId != null && !("".equals(rechargeId))) {
				Map<String, Object> recharge = rechargeSerivce
						.findDetail(Integer.parseInt(rechargeId));
				request.setAttribute("recharge", recharge);
				int userId = (Integer) recharge.get("user_id");
				Member user = memberProvider.findById(userId);
				request.setAttribute("user", user);
				AccountBank bankCard = memberAccountBankProvider.findByUserId(userId);
				request.setAttribute("bankCard", bankCard);
				Auth realName = certificationProvider.findByUserId(userId);
				request.setAttribute("realName", realName);
				request.setAttribute("logs",accountLogService.findPager(userId+"",null,null,null,null,0,20));
		}
		return "admin/account/record/recharge/input";
	}

	/**
	 * 充值审核
	 * 
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = { "/rechargeVerify" }, produces = { "application/json;charset=UTF-8" })
	@ResponseBody
	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "remark", message = "备注信息不能为空"),
			@RequiredStringValidator(fieldName = "rechargeId", message = "充值单号不能为空"),
			@RequiredStringValidator(fieldName = "status", message = "状态不能为空")

	})
	public synchronized Message rechargeVerify(HttpServletRequest request,
											   HttpSession session , @RequestParam(value = "rechargeId",required = false) Integer rechargeId
			, @RequestParam(value = "status",required = false) String status
			, @RequestParam(value = "remark",required = false) String remark
	)  {
				AdminUser emp = getCurrentEmp();
				AccountRecharge recharge = rechargeSerivce
						.findByIdStatus0(rechargeId);
				if (recharge == null) {
					throw new NoticeException("不要重复提交");
				}
				recharge.setStatus(Integer.parseInt(status));
				recharge.setVerify_userid(emp.getId());
				recharge.setVerify_time(MsDateUtils.getTime());
				recharge.setVerify_remark(remark);
				try {
					memberAccountProvider.rechargeVerify(recharge,request.getHeader("User-Agent"),AppContext.getRemoteIp(),emp,remark,status);
				}catch (Exception e){
					throw  new NoticeException("系统错误");
				}
				return  Message.success("充值成功");

	}

	@Override
	public boolean getBinderFlag() {
		return true;
	}
}
